import path from 'path';
import { execFileSync } from 'child_process';
import * as fs from 'fs';
import * as vscode from 'vscode';
import { ChatMessage } from '../../../../core';
import { Buffer } from 'buffer';

export interface APIData {
  "api": string,
  "filePath": string,
  "line": string,
  "startCol": string,
  "endCol": string,
  "guide": string,
  "level": string
}

export class ApiUsageAdapter{
  context: vscode.ExtensionContext;
  endAPILevel: number = 12;

  constructor(context: vscode.ExtensionContext) {
    this.context = context;
  }
  
  runPythonExe(exePath: string, args: any[]): string {
    try {
      // 关键配置：强制指定 UTF-8 编码和环境变量
      const options = {
        encoding: 'buffer' as const,  // 获取原始二进制数据
        env: {
          ...process.env,            // 继承当前环境变量
          PYTHONIOENCODING: 'utf-8', // 强制 Python 使用 UTF-8
          LC_ALL: 'en_US.UTF-8'      // 确保 Linux/macOS 兼容
        }
      };
  
      // 执行 EXE 并手动解码
      const stdoutBuffer = execFileSync(exePath, args, options);
      const stdout = stdoutBuffer.toString('utf-8').trim();
  
      // 调试用：打印原始字节（十六进制）
      // console.debug('原始字节:', stdoutBuffer.toString('hex'));
  
      return stdout;
    } catch (error) {
      console.error('执行 Python EXE 失败:');
      if (error instanceof Error && 'stderr' in error) {
        console.error('错误输出:', (error as any).stderr.toString('utf-8'));
      }
      throw error;
    }
  }

  
  getResourcePath = (context: vscode.ExtensionContext, relativePath: string): string => {
    return path.join(context.extensionPath, 'resource', relativePath);
  };

  getKnowledgePath = (context: vscode.ExtensionContext, relativePath: string): string => {
    return path.join(context.extensionPath, 'resource', 'ApiPilot', relativePath);
  };
  
  // 读取 JSON 文件
  readConfigFile = (context: vscode.ExtensionContext, jPath: string) => {
    const configPath = this.getResourcePath(context, jPath);
    const rawData = fs.readFileSync(configPath, 'utf-8');
    return JSON.parse(rawData);
  };
  
  /**
   * 读取指定路径的文件内容
   * @param filePaths 文件路径数组
   * @returns 包含文件内容的字符串
   */
  readFilesWithExtensions(filePaths: string) {
    let content = '';
    try {
      // 读取文件内容
      content = fs.readFileSync(filePaths, 'utf-8');
      // console.log('Received output:', content);
    } catch (error) {
      console.error(`读取文件 ${filePaths} 时出错:`, error);
    }
    return content;
  }
  
  APILocation(codePath: string[], startAPILevel: number, endAPILevel: number): any[] {
    this.endAPILevel = endAPILevel;
    // codePath要读取的扩展名
    let merged: any[] = [];
    const resourcePath = this.getResourcePath(this.context, 'ApiPilot');
    const exePath = this.getKnowledgePath(this.context, 'scene_judge.exe');
    for (const filePath of codePath) {
      // const fileContent = this.readFilesWithExtensions(filePath); 
      // run python
      const args = [
        filePath,
        startAPILevel.toString(),
        endAPILevel.toString(),
        resourcePath
      ];
      const result = this.runPythonExe(exePath, args);
      // 解析输出结果
      if (result.length >= 6) {
        const validJson = result.replace(/'/g, '"');
        const parsed = JSON.parse(validJson);
        merged = merged.concat(parsed);
      } else {
        console.log('无变更API');
      }
    }
    return merged;
  }
  
  // 实例输入：inputJson = {"api": "ForEach", "filePath": currentFilePath, "line": "20", "startCol": "", "endCol": "", "guide": ""}
  APIAdapter(inputJson: APIData) {
    const resourcePath = this.getResourcePath(this.context, 'ApiPilot');
    const jPath = path.join(resourcePath, "API" + inputJson['level'] + "_change.json");
    const exePath = this.getKnowledgePath(this.context, 'code_generation.exe');
    const fileContent = this.readFilesWithExtensions(inputJson['filePath']);
    const args = [
      inputJson['api'],
      inputJson['line'],
      jPath,
      this.endAPILevel.toString()
    ];
    const result = this.runPythonExe(exePath, args);
    console.log('Received output:', result);
    const prompt: ChatMessage[] = [
        {role: "user", content: result},
        {role: "user", content: fileContent},
    ];
    return prompt;
  }
}